#!/bin/bash

NODE_VERSION=node-v16.13.0-linux-x64
PROJECT_NAME=egg-server-template

# check node environment
if [ ! -d "./${NODE_VERSION}" ];then
  if [ -f "./${NODE_VERSION}.tar.xz" ];then
    echo "${NODE_VERSION}.tar.xz found, extracting..."
    tar xf ./${NODE_VERSION}.tar.xz
  else
    echo "Error: ${NODE_VERSION}.tar.xz not found. Please setup NODE environment."
    exit 1
  fi
fi


if [ -d "./${NODE_VERSION}" ];then
  echo "Using ${NODE_VERSION} for NODE environment"
  PATH=$PATH:`pwd`/${NODE_VERSION}/bin
  echo "node version: `node -v`"
  echo "npm version: `npm -v`"
else
  echo "NODE environment not found. Exiting..."
  exit 1
fi

# extract egg-server-template

if [ -f "./${PROJECT_NAME}.zip" ];then
  # old project exists, remove
  if [ -d "./${PROJECT_NAME}" ];then
    cd "./${PROJECT_NAME}"
    echo "Old project directory found. Stopping..."
    npm stop
    cd -
    echo "Removing old project directory..."
    rm -rf ./${PROJECT_NAME}
  fi
  echo "Extracting ./${PROJECT_NAME}.zip ..."
  unzip ./${PROJECT_NAME}.zip -d ./${PROJECT_NAME} > /dev/null
  NOW=`date "+%Y-%m-%d_%H-%M-%S"`
  echo "Backup: rename ./${PROJECT_NAME}.zip to ./${PROJECT_NAME}.zip.bak_${NOW}"
  mv ./${PROJECT_NAME}.zip ./${PROJECT_NAME}.zip.bak_${NOW}
  cd "./${PROJECT_NAME}"
  
  # add execute permission
  chmod +x ./node_modules/.bin/*

  echo "Building project source..."
  npm run tsc
  echo "Starting Service..."
  npm start
  cd -

else
  echo "No project archive file. do nothing."
fi

echo "Done!"